package de.clapp;

import java.util.ArrayList;

import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;

public abstract class BaseModel<D> implements LoaderCallbacks<D>
{
    protected Activity activity;

    protected ArrayList<IModelAdapter> listeners = new ArrayList<IModelAdapter>();

    protected D modelData;

    public void addListener(IModelAdapter adapter)
    {
        listeners.add(adapter);
        fireModelchanged();
    }

    public void removeListener(IModelAdapter adapter)
    {
        listeners.remove(adapter);
    }

    private void fireModelchanged()
    {
        if (modelData == null)
        {
            return;
        }
        for (IModelAdapter l : listeners)
        {
            System.out.println(modelData);
            l.setData(modelData);
        }
    }

    @Override
    public void onLoadFinished(Loader<D> loader, D data)
    {
        modelData = data;
        fireModelchanged();
    }

    @Override
    public void onLoaderReset(Loader<D> loader)
    {

    }

    public void loadData(Activity activity)
    {
        this.activity = activity;
        activity.getLoaderManager().initLoader(Settings.LOADERNUMBER++, null, this).forceLoad();
    }
}
